﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;

namespace TfsBugger.Util
{
    public class Set<T> : Collection<T>
        where T : IComparable
    {
        #region Ctors
        public Set()
        {

        }


        public Set(IList<T> list)
        {
            foreach (T t in list)
                Add(t);
        }


        public Set(IEnumerable<T> items)
        {
            AddRange(items);
        }


        public Set(params T[] items)
        {
            AddRange(items);
        }
        #endregion


        public void AddRange(IEnumerable<T> items)
        {
            foreach (T t in items)
                Add(t);
        }


        public bool RemoveIfPresent(T item)
        {
            if (Contains(item))
            {
                Remove(item);
                return true;
            }

            return false;
        }


        public void Sort(Comparison<T> comparison)
        {
            IEnumerable<T> items = from i in this
                                   orderby comparison
                                   select i;

            Clear();
            AddRange(items);
        }


        public bool TryAdd(T item)
        {
            if (!this.Contains(item))
            {
                Add(item);
                return true;
            }

            return false;
        }


        public bool TryRemove(T item)
        {
            if (this.Contains(item))
            {
                Remove(item);
                return true;
            }

            return false;
        }


        protected override void InsertItem(int index, T item)
        {
            if (!this.Contains(item))
                base.InsertItem(index, item);
        }


        public void ForEach(Action<T> action)
        {
            foreach (T item in this)
                action(item);
        }


        public T[] ToArray()
        {
            return new List<T>(this).ToArray();
        }
    }
}
